﻿/**
 * ...
 * @author Unknown
 */

import flash.geom.ColorTransform;
import kliment.math.Calc;

class kliment.display.MCColor {
	
	static function tint(pTarget:MovieClip, pColor:Object, pAlpha:Number, pMultiplier:Object):Void {
		setCT(pTarget, colorTransform(pColor, pAlpha, pMultiplier));
	}
	
	/**
	 * convert color string to color number
	 * @param	pString		color string in #COLOR or 0xCOLOR format
	 * @return	number of color
	 */
	static function toNumber(pString:String):Number {
		var length:Number = pString.length;
		
		if (pString.charAt(0) == "#") {
			return parseInt(pString.substring(1, length),16);
		} else {
			return parseInt(pString, 16);
		}
	}
	
	/**
	 * conver color number to color string
	 * @param	pNumber		number of color
	 * @param	p			indicate color format: p==true||1 #COLOR else 0xCOLOR
	 * @return	color string
	 */
	static function toString(pNumber:Number, p:Object):String {
		var str:String = pNumber.toString(16);
		while (str.length < 6) str = '0' + str;
		return (p)? ("#" + str) : ("0x" + str)
	};
	
	static function setCT(pMovieClip:MovieClip, ct:ColorTransform):Void {
		if (!ct) ct = colorTransform();
		pMovieClip.transform.colorTransform = ct;
	}
	
	static function getCT(pMovieClip:MovieClip):ColorTransform {
		return pMovieClip.transform.colorTransform;
	}
	
	static function colorTransform(pColor, pAlpha:Number, pMultiplier):ColorTransform {
		var rm:Number = 0;
		var gm:Number = 0;
		var bm:Number = 0;
		var am:Number = 1;
		
		var ro:Number = 0;
		var go:Number = 0;
		var bo:Number = 0;		
		var ao:Number = 0;
		
		if (pColor != undefined) {
			if (typeof(pColor) == 'string') {
				var str:String = (pColor.charAt(0) == '#')? pColor.substring(1, pColor.length):pColor.substring(2, pColor.length);
				ro = parseInt(str.substring(0,2), 16);
				go = parseInt(str.substring(2,4), 16);
				bo = parseInt(str.substring(4, 6), 16);
			} else if (typeof(pColor) == 'number') {
				return colorTransform(MCColor.toString(pColor), pAlpha, pMultiplier);
			}
			
			if (pAlpha != undefined) am = pAlpha/100;
			
			if (pMultiplier != undefined) {
				
				if (typeof(pMultiplier) == 'string') {
					var mStr:String = pMultiplier.substring(2, pMultiplier.length)
					
					rm = Calc.roundDec( parseInt( pMultiplier.substring(0, 2) , 16 ) / 255 , 2);
					gm = Calc.roundDec( parseInt( pMultiplier.substring(2, 4) , 16 ) / 255 , 2);
					bm = Calc.roundDec( parseInt( pMultiplier.substring(4, 6) , 16 ) / 255 , 2);
					
					if (isNaN(rm)) rm = 0;
					if (isNaN(gm)) gm = 0;
					if (isNaN(bm)) bm = 0;
				} else if (typeof(pMultiplier) != 'string') {
					colorTransform(pColor, pAlpha, MCColor.toString(pMultiplier));
				}
			}
			
		} else {
			rm = 1;
			gm = 1;
			bm = 1;					
		}
		
		return new ColorTransform(rm, gm, bm, am, ro, go, bo, ao);
	}
}